import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hj_crm/const/constant.dart';
import 'package:hj_crm/entity/perms_menu.dart';
import 'package:hj_crm/form/distributors/distributor_form.dart';
import 'package:hj_crm/form/distributors/distributor_list.dart';
import 'package:hj_crm/form/user_form.dart';
import 'package:hj_crm/form/user_list.dart';
import 'package:hj_crm/http/request_repository.dart';
import 'package:hj_crm/login/user_login.dart';
import 'package:hj_crm/utils/perms_check.dart';
import 'package:hj_crm/utils/sp_utils.dart';
import 'package:hj_crm/utils/toast_utils.dart';

class HomePageWidget extends StatefulWidget {
  const HomePageWidget({super.key});

  @override
  State<HomePageWidget> createState() => _HomePageWidgetState();
}

class _HomePageWidgetState extends State<HomePageWidget> {
  bool hasDrawer = false;
  bool isDistributorSystem = Constant.dualSystem;

  ///
  late VoidCallback _userListRefresh;
  late VoidCallback _distributorListRefresh;

  final RequestRepository repository = Get.find<RequestRepository>();

  PermsMenu? permsMenu;

  /// 拥有管理系统权限数量
  int _hasNum = 0;

  /// 管理系统是否有新增权限
  bool userHasAdd = true;
  bool distributorHasAdd = true;

  @override
  void initState() {
    super.initState();
    getPermissions();
  }

  /// 获取用户权限
  getPermissions() {
    repository.getPermissions(
      success: (data) {
        permsMenu = data;

        _handlePermsMenu();
        setState(() {});
      },
      fail: (code, msg) {
        ToastUtils.show('获取权限失败: code: $code, msg: $msg');
        print('code: $code, msg: $msg');
      },
    );
  }

  /// 处理权限及菜单
  void _handlePermsMenu() {
    if (permsMenu == null) return;
    permsMenu!.menus?.forEach((element) {
      if (element.type == 1 &&
          (element.router == '/content/customer' || element.router == '/content/customerInfo')) {
        _hasNum++;
      }
    });

    if (_hasNum == 0) {
      ToastUtils.show('无权限访问');
      return;
    }

    Constant.dualSystem = _hasNum >= 2;
    hasDrawer = Constant.dualSystem;
    isDistributorSystem = Constant.dualSystem;

    /// 处理权限
    PermsCheck.handlePermsMenu(permsMenu!);

    /// 是否有新增权限
    userHasAdd = PermsCheck.customerAdd();
    distributorHasAdd = PermsCheck.distributorAdd();
  }

  /// 更新系统
  void _systemChanged(bool distributor) {
    setState(() {
      isDistributorSystem = distributor;
    });
  }

  /// 跳转到新增用户页面
  void _gotoFormWidget() {
    if (Constant.dualSystem && isDistributorSystem) {
      Get.to(() => const DistributorFormWidget())?.then((value) {
        if (value == true) _distributorListRefresh();
      });
    } else {
      Get.to(() => const UserFormWidget())?.then((value) {
        if (value == true) _userListRefresh();
      });
    }
  }

  bool get _hasFloatingActionButton {
    if (_hasNum == 0) {
      return false;
    }
    if (isDistributorSystem) {
      return distributorHasAdd;
    } else {
      return userHasAdd;
    }
  }

  @override
  Widget build(BuildContext context) {
    return permsMenu == null
        ? Container(
            color: Colors.white,
            child: const Center(
              child: CircularProgressIndicator(),
            ),
          )
        : Scaffold(
            appBar: AppBar(
              leading: hasDrawer
                  ? Builder(
                      builder: (context) {
                        return IconButton(
                          icon: const Icon(Icons.menu),
                          onPressed: () {
                            Scaffold.of(context).openDrawer();
                          },
                        );
                      },
                    )
                  : null,
              title: isDistributorSystem ? const Text('健康产业客户营销专用') : const Text('用户信息管理'),
              actions: [
                Padding(
                  padding: EdgeInsets.only(right: 10),
                  child: IconButton(
                    icon: const Icon(
                      Icons.settings_power,
                    ),
                    color: Colors.black,
                    onPressed: () {
                      SpUtil.deleteToken();
                      PermsCheck.clear();
                      Get.off(const LoginPageWidget());
                    },
                  ),
                ),
              ],
            ),
            drawer: hasDrawer
                ? Drawer(
                    // Add a ListView to the drawer. This ensures the user can scroll
                    // through the options in the drawer if there isn't enough vertical
                    // space to fit everything.
                    child: ListView(
                      // Important: Remove any padding from the ListView.
                      padding: EdgeInsets.zero,
                      children: [
                        const DrawerHeader(
                          decoration: BoxDecoration(
                            color: Colors.blue,
                          ),
                          child: Center(
                            child: Text(
                              'CRM系统',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 24,
                              ),
                            ),
                          ),
                        ),
                        ListTile(
                          textColor: isDistributorSystem ? Colors.blue : null,
                          title: const Text('健康产业客户营销专用'),
                          onTap: () {
                            if (isDistributorSystem) {
                              Navigator.pop(context);
                              return;
                            }
                            _systemChanged(true);
                            Navigator.pop(context);
                          },
                        ),
                        ListTile(
                          // tileColor:
                          textColor: !isDistributorSystem ? Colors.blue : null,
                          title: const Text('用户信息管理'),
                          onTap: () {
                            if (!isDistributorSystem) {
                              Navigator.pop(context);
                              return;
                            }
                            _systemChanged(false);
                            Navigator.pop(context);

                            // Get.off(UserListWidget(
                            //   refreshAction: (refresh) => _userListRefresh = refresh,
                            // ));
                            // Navigator.pop(context);
                          },
                        ),
                      ],
                    ),
                  )
                : null,

            body: _hasNum == 0
                ? Center(
                    child: Container(
                      color: Colors.white,
                      child: const Center(
                        child: Text('无权限访问'),
                      ),
                    ),
                  )
                : isDistributorSystem
                    ? DistributorListWidget(
                        refreshAction: (refresh) => _distributorListRefresh = refresh,
                      )
                    : UserListWidget(
                        refreshAction: (refresh) => _userListRefresh = refresh,
                      ),

            /// 新增用户
            floatingActionButton: _hasFloatingActionButton
                ? FloatingActionButton(
                    onPressed: _gotoFormWidget,
                    tooltip: isDistributorSystem ? '添加客户' : '添加用户',
                    child: const Icon(Icons.add),
                  )
                : null, // This
          );
  }
}
